import { App } from '@capacitor/app';
import { setupPageProgress, setupPageTitle } from '@peng_kai/kit/admin/route-guards';
import { Modal } from 'ant-design-vue';
import { useLayout } from '~/layouts/default/useLayout';

export default defineRouteGuard({
  setup(router) {
    setupPageProgress(router);
    // setupPageTitle(router);
    const { asideContent, asideMenu } = useLayout();

    let backButtonPressedOnce = false;
    /** APP返回行为 */
    App.addListener('backButton', ({ canGoBack }) => {
      const popups = document.querySelectorAll('[class *="ant-cover__Modal"]');
      if (popups) {
        Modal.destroyAll();
        return;
      }
      if (!canGoBack) { // 使用 Capacitor 提供的 canGoBack 判断
        if (backButtonPressedOnce) {
          App.exitApp();
          return;
        }

        backButtonPressedOnce = true;
        setTimeout(() => (backButtonPressedOnce = false), 2000);

        // 提示用户再按一次退出
        return;
      }
      // 默认返回行为
      router.back();
    });

    router.afterEach((to, from) => {
      if (to.path !== from.path) {
        // 关闭所有全局弹窗
        Object.values(globalPopups).forEach(popup => popup.close?.());

        // 关闭左边菜单抽屉
        const asideMenuCloseable = asideMenu.state.open === 'full' && asideMenu.drawerOpened;
        asideMenuCloseable && asideMenu.toggle(false);

        // 关闭右侧内容抽屉
        const asideContentCloseable = asideContent.state.open === 'full' && asideContent.drawerOpened;
        asideContentCloseable && asideContent.toggle(false);
      }
    });
  },
});
